package com.lab.widget;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.cuitrip.apiservice.ServiceBusiness;
import com.cuitrip.app.base.UnitUtils;
import com.cuitrip.business.tripservice.TripDescriptionActivity;
import com.cuitrip.component.choicedialog.ChoiceDialog;
import com.cuitrip.component.choicedialog.MultiItem;
import com.cuitrip.service.R;
import com.cuitrip.util.ResourceUtil;
import com.lab.app.BaseActivity;
import com.lab.logtrack.AppLog;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.photopicker.EasyImage;
import com.lab.utils.ArrayUtil;
import com.lab.utils.Constants;
import com.lab.utils.LogHelper;
import com.lab.utils.MessageUtils;
import com.lab.utils.imageupload.imp.OssService;

import java.io.File;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created on 7/25.
 */
public class PicTextEditView extends LinearLayout implements ImageSelectView.OnImageClickdCallback {
    public static final String TAG = "PicTextEditView";

    private TextEditSplit mCurrentEdit;
    private int mPositionInEdit;
    private int mPositionInParent;
    private SoftReference<BaseActivity> mActivityReference;
    private ArrayList<String> mPictures = new ArrayList<String>();
    private OssService ossService;
    private String uid;

    public void setOssService(OssService ossService) {
        this.ossService = ossService;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    private void addWatcher(final EditText editText){
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                try {
                    int nSelStart = editText.getSelectionStart();
                    int nSelEnd = editText.getSelectionEnd();
                    int sumCount = textCount();
                    if (mContentChangeCallBack != null) {
                        boolean nOverMaxLength = (sumCount > 7500) ? true : false;
                        mContentChangeCallBack.onTextCountChanged(sumCount);
                        if (nOverMaxLength) {
                            editable.delete(nSelStart - 1, nSelEnd);
                            mCurrentEdit.setTextKeepState(editable);
                        }
                    }
                } catch (Exception e) {
                    AppLog.w(e.toString());
                }
            }
        });

    }


    private List<String> mUrlsToDeleted = new ArrayList<String>();

    public PicTextEditView(Context context) {
        super(context);
        init();
    }

    public PicTextEditView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PicTextEditView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setOrientation(VERTICAL);
    }

    public void setActivity(BaseActivity activity) {
        mActivityReference = new SoftReference<>(activity);
    }

    public BaseActivity getActivity(){
        if (mActivityReference != null && mActivityReference.get() != null){
            return mActivityReference.get();
        }
        return null;
    }

    public void initDesc(String desc, String mainPic, List<String> picList) {
        if (TextUtils.isEmpty(desc)) {
            TextEditSplit textEditSplit = new  TextEditSplit(getContext());
            textEditSplit.setHint(R.string.trip_attribute_description_desc_2);
            textEditSplit.setHintTextColor(getContext().getResources().getColor(R.color.ganshi_ded8d7));
            addView(textEditSplit);
            addWatcher(textEditSplit);
        } else {
            generateView(desc, mainPic, picList);
        }
    }

    private void generateView(String desc, String mainPic, List<String> picList) {
        if (getActivity() == null){
            return;
        }
        Pattern pattern = Pattern.compile(Constants.IMAGE_PATTERN);
        Matcher matcher = pattern.matcher(desc);
        int index = 0;
        while (matcher.find()) {
            int start = matcher.start();
            String temp = desc.substring(index, start);
            index = matcher.end();
            if (!TextUtils.isEmpty(temp)) {
                TextEditSplit editSplit = new TextEditSplit(getActivity());
                editSplit.setText(temp);
                addView(editSplit);
                addWatcher(editSplit);
            }
            String picIndex = matcher.group(1);
            LogHelper.d(TAG, "url: " + picIndex);
            if (!TextUtils.isEmpty(picIndex)) {
                ImageSelectView view = new ImageSelectView(getActivity());
                int i = 0;
                try {
                    i = Integer.parseInt(picIndex);
                }catch (Exception e){

                }
                if (ArrayUtil.isIndexSafe(i, picList)){
                    String pic = picList.get(i);
                    view.setRemoteUrl(pic, true);
                    if (picList.get(i).equals(mainPic)) {
                        view.setSelected(true);
                    }
                }

                view.setOnImageClickdCallback(this);
                if (getChildAt(getChildCount() - 1) instanceof ImageSelectView) {
                    TextEditSplit textEditSplit = new TextEditSplit(getActivity());
                    addView(textEditSplit);
                    addWatcher(textEditSplit);
                }
                addView(view);
            }
        }
        if(index < desc.length() - 1){
            TextEditSplit editSplit = new TextEditSplit(getActivity());
            editSplit.setText(desc.substring(index, desc.length()));
            addWatcher(editSplit);
            addView(editSplit);
        }
        int childCount = getChildCount();
        if (childCount == 0 || getChildAt(0) instanceof ImageSelectView) {
            TextEditSplit textEditSplit = new TextEditSplit(getActivity());
            addWatcher(textEditSplit);
            addView(textEditSplit, 0);
        }
        childCount = getChildCount();
        if (childCount > 0 && getChildAt(childCount - 1) instanceof ImageSelectView) {
            TextEditSplit textEditSplit = new TextEditSplit(getActivity());
            addWatcher(textEditSplit);
            addView(textEditSplit, childCount);
        }
    }

    public String generateDesc() {
        mPictures.clear();
        StringBuilder sb = new StringBuilder();
        int count = getChildCount();
        int picIndex = 0;
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            if (child instanceof TextEditSplit) {
                TextEditSplit textEditSplit = (TextEditSplit) child;
                String content = textEditSplit.getText().toString();
                if (!TextUtils.isEmpty(content)) {
                    sb.append(content);
                }
            } else if (child instanceof ImageSelectView) {
                ImageSelectView imageSelectView = (ImageSelectView) child;
                if (!TextUtils.isEmpty(imageSelectView.getRemoteUrl())) {
                    sb.append(generationImageIndex(picIndex));
                    mPictures.add(imageSelectView.getRemoteUrl());
                    picIndex++;
                }
            }
        }
        return sb.toString();
    }

    private String generationImageIndex(int index){
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(Constants.IMAGE_LEFT).append("P");
        if (index < 10){
            stringBuilder.append("00");
            stringBuilder.append(index);
        }else{
            stringBuilder.append("0");
            stringBuilder.append(index);
        }
        stringBuilder.append(Constants.IMAGE_RIGHT);
        return stringBuilder.toString();
    }

    public ArrayList<String> getPictures() {
        return mPictures;
    }

    public boolean isUpdating() {
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            if (getChildAt(i) instanceof ImageSelectView) {
                if (((ImageSelectView) getChildAt(i)).isUpdating()) {
                    return true;
                }
            }
        }
        return false;
    }

    public void addImage() {
        if (getActivity() == null){
            return;
        }
        int childCount = getChildCount();
        int picCount = 0;
        for (int i = 0; i < childCount; i++) {
            if (getChildAt(i) instanceof ImageSelectView) {
                ++picCount;
            }
        }
        if (picCount >= 9) {
            MessageUtils.createHoloBuilder(getActivity()).setMessage(getContext().getString(R.string.operation_upload_photo_limit_1,9))
                    .setPositiveButton(R.string.operation_ok_2, null).show();
            return;
        }

        View foucs = findFocus();
        if (foucs == null || !(foucs instanceof TextEditSplit)) {
            //MessageUtils.showToast(R.string.ct_select_pic_poition);
            return;
        }
        mCurrentEdit = (TextEditSplit) foucs;
        AppLog.d(" not null="+mCurrentEdit);
        mPositionInParent = indexOfChild(mCurrentEdit);
        mPositionInEdit = mCurrentEdit.getSelectionStart();
        EasyImage.openChooser(getActivity(),"",true);
    }

    /**
     * 获取照片数目
     * @return 返回照片数目
     */
    public int pictureCount(){
        int childCount = getChildCount();
        int picCount = 0;
        for (int i = 0; i < childCount; i++) {
            if (getChildAt(i) instanceof ImageSelectView) {
                ++picCount;
            }
        }
        return picCount;
    }

    /**
     * 返回文字数目
     * @return
     */
    public int textCount(){
        int childCount = getChildCount();
        int textCount = 0;
        for (int i = 0; i < childCount; i++) {
            if (getChildAt(i) instanceof TextEditSplit) {
                textCount += ((TextEditSplit)getChildAt(i)).length();
            }
        }
        return textCount;
    }

    public void addTakePhotoImage(int requestCode,File file) {
        if (getActivity() == null) {
            return;
        }
        int picCount = pictureCount();
        if (picCount >= 9) {
            MessageUtils.createHoloBuilder(getActivity()).setMessage(getContext().getString(R.string.operation_upload_photo_limit_1,9))
                    .setPositiveButton(R.string.operation_ok_2, null).show();
            return;
        }

        View foucs = findFocus();
        if (foucs == null || !(foucs instanceof TextEditSplit)) {
            //MessageUtils.showToast(R.string.ct_select_pic_poition);
            return;
        }
        mCurrentEdit = (TextEditSplit) foucs;
        mPositionInParent = indexOfChild(mCurrentEdit);
        mPositionInEdit = mCurrentEdit.getSelectionStart();
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", UnitUtils.IMAGE_CROP_WIDTH);// 裁剪框比例
        intent.putExtra("aspectY", UnitUtils.IMAGE_CROP_HEIGHT);
        getActivity().startActivityForResult(intent, requestCode);
    }

    private void updateImage(final ImageSelectView view, File imageFile) {
        if (getActivity() == null){
            return;
        }
        final TripDescriptionActivity tripDescriptionActivity = (TripDescriptionActivity) getActivity();
        if (ossService == null) {
            tripDescriptionActivity.requestImageToken();
            return;
        }
        tripDescriptionActivity.showLoading();
        ossService.asyncPutImage(OssService.getObjectName(uid, imageFile), imageFile.getAbsolutePath(), new OssService.UploadCallback() {
            @Override
            public void onFailure(String errorMessage) {
                tripDescriptionActivity.hideLoading();
                if (!TextUtils.isEmpty(errorMessage)) {
                    MessageUtils.showToast(errorMessage);
                }
                removeImageView(view);
            }

            @Override
            public void onSuccess(String url) {
                tripDescriptionActivity.hideLoading();
                view.setRemoteUrl(url, false);
            }

            @Override
            public void onProgress(int progress) {
            }
        });
    }

    public void insertImage(Bitmap bp, File imageFile) {
        if (getActivity() == null){
            return;
        }
        ImageSelectView view = new ImageSelectView(getContext());
        view.setOnImageClickdCallback(this);
        view.setImageBitmap(bp);
        updateImage(view, imageFile);
        int childCount = getChildCount();
        boolean firstImage = true;
        for (int i = 0; i < childCount; i++) {
            if (getChildAt(i) instanceof ImageSelectView) {
                firstImage = false;
                break;
            }
        }
        if (firstImage) {
            view.setSelected(true);
        }
        if (mCurrentEdit == null){
            View currentView = getChildAt(mPositionInParent);
            if (currentView instanceof TextEditSplit){
                mCurrentEdit = (TextEditSplit) currentView;
            }else{
                return;
            }
        }
        Editable text = mCurrentEdit.getText();
        if (mPositionInEdit == 0) {
            addView(view, mPositionInParent);
            TextEditSplit textEditSplit = new TextEditSplit(getActivity());
            addWatcher(textEditSplit);
            addView(textEditSplit, mPositionInParent);
        } else if (mPositionInEdit >= text.length()) {
            boolean isEnd = mPositionInParent == getChildCount() - 1;
            boolean isMiddle = false;
            if (!isEnd) {
                isMiddle = getChildAt(mPositionInParent + 1) instanceof ImageSelectView;
            }
            addView(view, mPositionInParent + 1);
            if (isEnd) {
                TextEditSplit textEditSplit = new TextEditSplit(getActivity());
                addWatcher(textEditSplit);
                addView(textEditSplit, getChildCount());
            } else if (isMiddle) {
                TextEditSplit textEditSplit = new TextEditSplit(getActivity());
                addWatcher(textEditSplit);
                addView(textEditSplit, mPositionInParent + 2);
            }
        } else {
            TextEditSplit newEdit = new TextEditSplit(getActivity());
            newEdit.setText(text.subSequence(mPositionInEdit, text.length()));
            addWatcher(newEdit);
            addView(view, mPositionInParent + 1);
            addView(newEdit, mPositionInParent + 2);
            mCurrentEdit.setText(text.subSequence(0, mPositionInEdit));
        }
        if (mContentChangeCallBack != null){
            mContentChangeCallBack.onImageCountChanged(pictureCount());
        }
    }

    private void removeImageView(ImageSelectView view) {
        int index = indexOfChild(view);
        if ((index > 0) && (index < getChildCount() - 1)) {
            View after = getChildAt(index + 1);
            View before = getChildAt(index - 1);
            if (after instanceof TextEditSplit && before instanceof TextEditSplit) {
                ((TextEditSplit) before).setText(((TextEditSplit) before).getText().toString()
                        + ((TextEditSplit) after).getText().toString());
                removeView(after);
            }
        }
        removeView(view);
        if (mContentChangeCallBack != null){
            mContentChangeCallBack.onImageCountChanged(pictureCount());
        }
    }

    @Override
    public void onImageSelected(ImageSelectView view) {
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            if (child instanceof ImageSelectView) {
                ((ImageSelectView) child).setSelected(false);
            }
        }
        view.setSelected(true);
    }

    @Override
    public void onImageClick(final ImageSelectView imageSelectView) {
        if (getActivity() == null){
            return;
        }
        final ChoiceDialog dialog = ChoiceDialog.getInstance();
        dialog.setDialogTitleVisibility(false);
        List<MultiItem> multiItemList = new ArrayList<MultiItem>();

        MultiItem deleteItem = new MultiItem(ResourceUtil.getString(R.string.operation_delete));
        multiItemList.add(deleteItem);

        final MultiItem cancelItem = new MultiItem(ResourceUtil.getString(R.string.operation_cancel));
        multiItemList.add(cancelItem);

        dialog.setDialogMessageVisibility(false);
        dialog.setDialogMultiStyleSetting(multiItemList, new ChoiceDialog.DialogStyleMultiCallback() {
            @Override
            public boolean onMultiItemClick(MultiItem multiItem, int position) {
                dialog.dismiss();
                if (position == 0) {
                    imageSelectView.destroy();
                    removeImageView(imageSelectView);
                    if (!TextUtils.isEmpty(imageSelectView.getRemoteUrl())) {
                        mUrlsToDeleted.add(imageSelectView.getRemoteUrl());
                    }
                    return true;
                }
                return false;
            }
        });
        getActivity().showDialogFragment(dialog);
    }

    public void deletePictures(){
        if (getActivity() == null){
            return;
        }
        if(mUrlsToDeleted.isEmpty()){
            return;
        }
        ApiProxy apiProxy = new ApiProxy(new IProxyCallback() {
            @Override
            public boolean onProxyResult(ProxyResult<?> result) {
                return false;
            }
        });

        for(String url :mUrlsToDeleted){
            ServiceBusiness.delPic(apiProxy, url);
        }
    }

    private ContentChangeCallBack mContentChangeCallBack;

    public ContentChangeCallBack getmContentChangeCallBack() {
        return mContentChangeCallBack;
    }

    public void setmContentChangeCallBack(ContentChangeCallBack mContentChangeCallBack) {
        this.mContentChangeCallBack = mContentChangeCallBack;
    }

    public interface ContentChangeCallBack{

        public void onImageCountChanged(int imageCount);

        public void onTextCountChanged(int textCount);

    }
}
